<template>
	<n-modal v-model:show="modalVisible" preset="card" :title="title" class="w-500px">
		<n-form ref="formRef" label-placement="left" :label-width="80" :model="formModel" :rules="rules">
			<n-grid :cols="24" :x-gap="18">
				<n-form-item-grid-item :span="24" label="活动名称" path="name">
					<n-input v-model:value="formModel.name" />
				</n-form-item-grid-item>
				<n-form-item-grid-item :span="24" label="商品代码" path="code">
					<n-input v-model:value="formModel.code" />
				</n-form-item-grid-item>
				<n-form-item-grid-item :span="24" label="秒杀时间" path="seckillTime">
					<n-date-picker type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
						v-model:formatted-value="formModel.seckillTime" />
				</n-form-item-grid-item>
			</n-grid>
			<n-space class="w-full pt-16px" :size="24" justify="end">
				<n-button class="w-72px" @click="closeModal">取消</n-button>
				<n-button class="w-72px" type="primary" @click="handleSubmit">确定</n-button>
			</n-space>
		</n-form>
	</n-modal>
</template>

<script setup lang="ts">
import { ref, computed, reactive, watch } from 'vue';
import type { FormInst, FormItemRule } from 'naive-ui';
import { createRequiredFormRule } from '@/utils';
import { AddOrUpdateIQIYISeckill } from "@/service";

export interface Props {
	/** 弹窗可见性 */
	visible: boolean;
	/**
	 * 弹窗类型
	 * add: 新增
	 * edit: 编辑
	 */
	type?: 'add' | 'edit';
	/** 编辑的表格行数据 */
	editData?: Seckill.IQIYISeckill | null;
}

export type ModalType = NonNullable<Props['type']>;

defineOptions({ name: 'TableActionModal' });

const props = withDefaults(defineProps<Props>(), {
	type: 'add',
	editData: null
});

interface Emits {
	(e: 'update:visible', visible: boolean): void;
	(e: 'onConfirm'): void;
}

const emit = defineEmits<Emits>();

const modalVisible = computed({
	get() {
		return props.visible;
	},
	set(visible) {
		emit('update:visible', visible);
	}
});
const closeModal = () => {
	modalVisible.value = false;
};

const title = computed(() => {
	const titles: Record<ModalType, string> = {
		add: '添加秒杀',
		edit: '编辑秒杀'
	};
	return titles[props.type];
});

const formRef = ref<HTMLElement & FormInst>();

type FormModel = Pick<Seckill.IQIYISeckill, 'name' | 'code' | 'seckillTime'>;

const formModel = reactive<FormModel>(createDefaultFormModel());

const rules: Record<keyof FormModel, FormItemRule | FormItemRule[]> = {
	name: createRequiredFormRule('请输入活动名称'),
	code: createRequiredFormRule('请输入商品Code'),
	seckillTime: createRequiredFormRule('请输入秒杀时间')
};

function createDefaultFormModel(): FormModel {
	return {
		name: '',
		code: '',
		seckillTime: null
	};
}

function handleUpdateFormModel(model: Partial<FormModel>) {
	Object.assign(formModel, model);
}

function handleUpdateFormModelByModalType() {
	const handlers: Record<ModalType, () => void> = {
		add: () => {
			const defaultFormModel = createDefaultFormModel();
			handleUpdateFormModel(defaultFormModel);
		},
		edit: () => {
			if (props.editData) {
				handleUpdateFormModel(props.editData);
			}
		}
	};

	handlers[props.type]();
}

async function handleSubmit() {
	await formRef.value?.validate();
	let input: Seckill.AddOrUpdateIQIYISeckillInput = {
		id: props.editData?.id,
		name: formModel.name,
		code: formModel.code,
		seckillTime: formModel.seckillTime
	}
	var data = await AddOrUpdateIQIYISeckill(input);
	if (!data.error) {
		window.$message?.success('保存成功!');
		emit('onConfirm'); // 触发回调事件
		closeModal();
	}
}

watch(
	() => props.visible,
	newValue => {
		if (newValue) {
			handleUpdateFormModelByModalType();
		}
	}
);
</script>

<style scoped></style>
